# -*- coding: utf-8 -*-
"""
@Time : 2024/4/4 19:58
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : publish_short.py
"""
import time
import logging
from selenium.webdriver.common.keys import Keys

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='jd_finance.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger(__name__)


def publish_short(driver, new):
    """
    发布短动态
    :param driver: 浏览器对象
    :param new: 单一一个新闻
    :return:
    """
    new_title = new['title']
    # 发布动作
    time.sleep(5)
    publish_url = "https://creator.jr.jd.com/#/publish/activity"
    logger.info("开始打开动态发布页面")
    on = True
    while on:
        try:
            driver.get(publish_url)
            logger.info("成功打开动态发布页面")
        except Exception as err:
            logger.error(f"打开动态发布页面失败！{err}")
            time.sleep(10)
        else:
            on = False

    time.sleep(10)
    # # 点击选择 短动态
    # logger.info("开始定位短动态按钮")
    # short_btn = driver.find_element_by_class_name("el-row").find_element_by_class_name("el-icon-if-activity")
    # short_btn.click()
    # logger.info("成功点击短动态按钮")

    # 查找短动态正文输入框并输入正文内容
    for _ in range(10):
        try:
            context = driver.find_element_by_class_name('ql-blank')
            # 先清空处理
            logger.info("首先清空可能存在的短动态正文内容")
            context.clear()

            context.send_keys(new['content_text'])
            context.send_keys(Keys.ENTER)
            logger.info(f"成功输入短动态：{new_title}的正文内容")
        except Exception as err:
            logger.error(f"短动态正文输入框设置报错：{err}")
            time.sleep(10)
        else:
            break

    # 设置圈子
    items = driver.find_elements_by_class_name("item")
    for item in items:
        try:
            item_label_name = item.find_element_by_class_name("item-label").text
            if item_label_name == "圈子":
                # print("成功找到圈子")
                quan_zi = item.find_element_by_class_name("el-button")
                quan_zi.click()
                logger.info("成功点击圈子")
                time.sleep(10)
                logger.info("开始定位圈子查询框")
                search_quanzi = driver.find_element_by_class_name("el-dialog__body").find_element_by_class_name(
                    "el-input__inner")
                logger.info("成功定位圈子查询框")
                logger.info("开始输入圈子名称")
                search_quanzi.send_keys("每日行情播报")
                logger.info("成功输入圈子名称")
                time.sleep(5)
                search_quanzi.send_keys(Keys.ENTER)
                logger.info("开始点击圈子搜索结果+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                driver.find_element_by_class_name("el-select-dropdown__item").click()
                logger.info("成功点击圈子搜索结果+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                break
        except Exception as err:
            logger.error(f"短动态设置圈子报错：{err}")
            continue

    # 设置话题
    items = driver.find_elements_by_class_name("item")
    logger.info("开始设置话题")
    for item in items:
        try:
            item_label_name = item.find_element_by_class_name("item-label").text
            if item_label_name == "话题":
                # print("成功找到话题")
                logger.info("成功找到话题")
                topic = item.find_element_by_class_name("el-button")
                driver.get_screenshot_as_file("点击短动态话题添加button.png")
                try:
                    topic.click()
                except Exception:
                    driver.execute_script("arguments[0].click()", topic)
                # topic.click()
                logger.info("成功点击话题")
                time.sleep(10)
                logger.info("开始定位话题查询框")
                search_topic = driver.find_element_by_class_name("el-dialog__body").find_element_by_class_name(
                    "el-input__inner")
                logger.info("成功定位话题查询框")
                search_topic.send_keys("#今日股市快乐炒股#")
                time.sleep(5)
                search_topic.send_keys(Keys.ENTER)
                logger.info("开始点击话题搜索结果+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                driver.find_element_by_class_name("el-select-dropdown__item").click()
                logger.info("成功点击话题搜索结果+++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
                break
        except Exception as err:
            logger.error(f"短动态设置话题报错：{err}")
            continue

    time.sleep(5)

    # 点击发布
    logger.info("开始查找短动态发布按钮")
    try:
        btns = driver.find_elements_by_class_name("el-button--primary")
        for publish_btn in btns:
            if publish_btn.text == "发布":
                logger.info("成功找到发布按钮")
                driver.execute_script("arguments[0].click()", publish_btn)
                # # 寻找提示框中的确定按钮
                # sure_btn = driver.find_element_by_class_name("el-message-box").find_element_by_class_name(
                #     "el-button--medium")
                # logger.info(f"找到了确定按钮,按钮上的文字是：{sure_btn.text}。")
                # sure_btn.click()
                # 发布成功保存到published_news.txt文件中
                time.sleep(5)
                driver.refresh()
                logger.info(f"成功发布，将短动态{new_title}保存至published_news.txt")
                with open("published_news.txt", "a", encoding='utf-8') as f:
                    print(new_title, file=f)
                break
    except Exception:
        logger.error(f"{new_title}发布失败或者超出发布次数,不会保存新闻标题到published_news.txt")
